package com.example.pagingdemo;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.pagingdemo.databinding.ActivityPagingBinding;
import com.example.pagingdemo.databinding.ActivityPagingRefreshBinding;
import com.example.pagingdemo.model.GithubUser;
import com.example.pagingdemo.paging.githubuser.GithubUserPageListAdapter;
import com.example.pagingdemo.paging.githubuser.GithubUserViewModel;

/**
 * @author: tuyrt7 on 2020/9/9.
 */
public class ItemKeyActivity extends AppCompatActivity {

    private ActivityPagingRefreshBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_paging_refresh);

        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerView.setHasFixedSize(true);
        GithubUserPageListAdapter adapter = new GithubUserPageListAdapter();
        mBinding.recyclerView.setAdapter(adapter);

        GithubUserViewModel viewModel = new ViewModelProvider(this).get(GithubUserViewModel.class);
        viewModel.getPageData().observe(this, new Observer<PagedList<GithubUser>>() {
            @Override
            public void onChanged(PagedList<GithubUser> users) {
                adapter.submitList(users);
                finishRefresh();
            }
        });

        mBinding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                viewModel.refresh();
            }
        });
    }

    private void finishRefresh() {
        if (mBinding.swipeRefresh != null && mBinding.swipeRefresh.isRefreshing()) {
            mBinding.swipeRefresh.setRefreshing(false);
        }
    }
}
